package com.lytest.cloud.amqp;

import com.lytest.cloud.bean.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AmqpTest {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    AmqpAdmin   amqpAdmin;

    //  创建exchange
    @Test
    public void createExchange(){
        amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
        System.out.println("创建完成！");
    }

    //  创建Queues
    @Test
    public void createQueue(){
        amqpAdmin.declareQueue(new Queue("lytest.queue",true));
        System.out.println("创建完成！");
    }

    //  创建Binding
    @Test
    public void createBinding(){
        amqpAdmin.declareBinding(new Binding("lytest.queue",Binding.DestinationType.QUEUE,"amqpadmin.exchange","lytest.queue",null));
        System.out.println("绑定完成！");
    }

    //点对点发送消息 单播
    @Test
    public void contextloads(){
        //需要自己构造一个Message,定义消息体内容和消息头
//        rabbitTemplate.send(exchange,routeKey,message);

        //Object默认当成消息体，只需要传入要发送的对象，自动序列化发送给rabbitmq
//        rabbitTemplate.convertAndSend(exchange,routekey,object);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","第一条消息");
        map.put("data", Arrays.asList("helloword",123,true));
        //对象被默认序列化以后发送出去
        rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);

    }

    //接收数据，如何将数据自动的转为json发送出去
    @Test
    public void  receive(){
//        接收的消息Message，既有消息头，也有消息体
//        rabbitTemplate.receive();

//        直接把消息体Message转换成想要的对象Object
//       rabbitTemplate.receiveAndConvert();
        Object object= rabbitTemplate.receiveAndConvert("atguigu.news");
        System.out.println(object.getClass());
        System.out.println(object);
    }
    //广播
    @Test
    public void sendMsg(){
        rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","罗汉中"));
    }
}
